<?php

/**
 * 手机短信发送
 *
 * @author  zhanglei<firenzelei@163.com>
 * @date    2017年03月30日
 *
 * Helper("Sms")->send('rebuildcache', $msg, $title, 'rebuildcache');
 */
namespace Helper;

class Sms
{
    /**
     * 短信发送接口地址
     */
    protected $url = 'http://alert.nutsapi.com/index.php?';

    /**
     * 是否发送短信
     */
    protected $message_open = 0;

    /**
     * 短信收件人组
     */
    protected $message_group = '';

    /**
     * 短信发送
     *
     * @param   string  $group  业务简称,必须填写。业务会对应收件人组
     * @param   string  $msg    短信内容,必须填写
     * @param   string  $title  短信标题,可以不填
     * @param   string  $md5    重复告警的唯一值,有重复告警十分钟内只发送一份。可以不填,会把url请求当成唯一值
     * @param   string  $type   发送方式,可以不填,默认sms
     *
     */
    function send($plate, $msg, $title='', $md5='', $type='sms')
    {
        $this->checkConfig($plate);
        //检查参数是否正确
        $response = $this->checkParams($plate, $msg);
        //拼接url的get参数
        $group = is_array($response) ? '' : $response;
        $md5 = ($md5=='') ? '' : md5($md5);
        $title .= ':'.gethostname();
        $params = ['group','msg','title','md5','type'];
        foreach ($params as $param)
        {
            $data[$param] = $$param;
        }
        $data = urldecode(http_build_query($data));
        $url = $this->url.$data;
        //只有在上面未报错的情况下，才去curl短信api
        if(!is_array($response))
        {
            $response = $this->doCurl($url);
        }
        //记录日志
        $this->log($url, $response);
    }

    function checkConfig($plate)
    {
        $sms_config = C('SMS_CONFIG');
        $sms_message_config = $sms_config[$plate];
        if(!empty($sms_message_config))
        {
            $this->message_open = $sms_message_config['message_open'];
            $this->message_group = $sms_message_config['message_group'];
        }
    }

    function checkParams($plate, $msg)
    {
        if(empty($plate) || empty($msg))
            return ["status"=>"失败","msg"=>"业务简称和短信内容不能为空"];
        //业务类型对应的邮件组
        $group = $this->message_group;
        if(empty($group))
        {
            return ["status"=>"失败","msg"=>"未能在配置文件中找到对应的用户组{$plate}"];
        }
        return $group;
    }

    /**
     * curl 请求发送短信接口地址
     * @param $url
     * @return array
     */
    function doCurl($url)
    {
        if(!$this->message_open)
        {
            return ["status"=>"失败","msg"=>"配置项中message_open为0,禁止发送短信"];
        }
        //10秒超时
        $time_out = 10;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, $time_out);
        $data = curl_exec($curl);
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        //重试一次
        if(false===$data)
            $data = curl_exec($curl);
        //curl请求失败
        if($http_code!=200)
            return ["status"=>"失败","msg"=>"curl请求失败,http_code:{$http_code}"];
        //返回数据错误提示
        $dataArr = json_decode($data, true);
        if($dataArr['code']!=200)
            return ["status"=>"失败","msg"=>"短信接口返回错误: {$data}"];
        return ["status"=>"成功","msg"=>"短信发送成功"];
    }

    /**
     * 记录短信发送的日志  Data/Uploads/affiliate/messagealert
     * @param   string    $url
     * @param   array     $response
     */
    function log($url, $response)
    {
        $dir = ATTACH_PATH . "affiliate/";
        if (!is_dir($dir))
        {
            mkdir($dir, 0777, true);
        }
        $filename = $dir.'messagealert';
        $msg = date("Y-m-d H:i:s")."\t"."短信发送{$response['status']}\tAPI地址:{$url}\t{$response['msg']}";
        file_put_contents($filename, $msg.PHP_EOL, FILE_APPEND | LOCK_EX);
    }

}